const express = require('express')
const { expressjwt } = require('express-jwt')
const jwtconfig = require('./jwt_config')
const loginRouter = require('./router/login')
const morgan = require('morgan')
const cors = require('cors')
const bodyParser = require('body-parser')
const Joi = require('joi')

const app = express()

app.use(cors())
app.use(morgan('dev'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use((req, res, next) => {
    res.cc = (err, status = 1) => {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})
app.use(expressjwt({
    secret: jwtconfig.jwtSecretKey,
    algorithms: ['HS256']
}).unless({
    path: [/^\/api\//]
}))
app.use('/api', loginRouter)
app.use((req, res, next) => {
    if (err instanceof Joi.ValidationError) return res.cc(err)
})

app.listen(3007, () => {
    console.log('服务器已启动');
})